from extensions import db
from flask import current_app

from data_modules.database_handler import DatabaseHandler
from utils.baidu_map_api import BaiduMapAPI


class LocationService:
    def __init__(self):
        self.map_api = BaiduMapAPI(api_key=current_app.config['BAIDU_MAP_API_KEY'])
        self.attraction_handler = DatabaseHandler(db.session.query(Attraction).statement)

    def get_nearest_attraction(self, user_location):
        """
        根据用户位置获取最近景点
        :param user_location: 用户当前位置坐标字符串（格式：纬度,经度）
        """
        try:
            # 获取所有景点数据
            attractions = self.attraction_handler.build_query().get_all()
            
            # 调用百度地图API计算距离
            nearest = None
            min_distance = float('inf')
            
            for attr in attractions:
                result = self.map_api.get_driving_direction_url(
                    origin=user_location,
                    destination=f"{attr.latitude},{attr.longitude}",
                    tactics=12  # 使用百度地图的"最短距离"策略
                )
                if result.get('distance') < min_distance:
                    min_distance = result['distance']
                    nearest = attr
            
            return nearest
        
        except Exception as e:
            current_app.logger.error(f"获取最近景点失败: {str(e)}")
            return None